package com.misty.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.misty.auth.component.LoginUser;
import com.misty.dao.domain.Users;
import com.misty.dao.mapper.MenuMapper;
import com.misty.dao.mapper.UsersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);
        Users user=usersMapper.selectOne(wrapper);
        log.info("======查找用户======");
        log.info(user.toString());
        //判断用户为空
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名错误！！");
        }

        //获取用户权限，并把其添加到GrantedAuthority中
//        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
//        GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(user.getRole());
//        grantedAuthorities.add(grantedAuthority);

        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        log.info("======查找权限======");
        log.info(list.toString());
        return new LoginUser(user,list);
    }
}
